package com.iflytek.jzcpx.procuracy.ocr.recognize;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iflytek.jzcpx.procuracy.ocr.common.constant.Constants;
import com.iflytek.jzcpx.procuracy.ocr.common.enums.RecognizeFuncEnum;
import com.iflytek.jzcpx.procuracy.ocr.recognize.model.Wjtz;
import com.iflytek.jzcpx.procuracy.tools.cont.ContClient;
import com.iflytek.jzcpx.procuracy.tools.cont.model.AcDto;
import com.iflytek.jzcpx.procuracy.tools.cont.model.Catalog;
import com.iflytek.jzcpx.procuracy.tools.cont.model.CatalogInfoDTO;
import com.iflytek.jzcpx.procuracy.tools.ocr.pdf.Page;
import com.iflytek.jzcpx.procuracy.tools.ocr.pdf.Rect;
import com.iflytek.jzcpx.procuracy.tools.ocr.pdf.TaskResult;
import com.iflytek.jzcpx.procuracy.tools.ocr.pdf.TextRegion;
import com.iflytek.jzcpx.procuracy.tools.ocr.pdf.Textline;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.text.WordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 图像识别 - 功能处理器
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2019-08-13 10:17
 */
@Component
public class RecognizeFuncHandler {

    @Autowired
    private ContClient contClient;

    /**
     * 处理 ocr 结果, 返回图像特征数据
     *
     * @param funcEnum 功能枚举
     * @param ocrJson  ocr 识别结果
     *
     * @return
     */
    public List<Wjtz> handle(RecognizeFuncEnum funcEnum, String ocrJson) {
        List<Wjtz> list = new ArrayList<>();
        JSONObject root = JSONObject.parseObject(ocrJson);
        TaskResult taskResult = JSONObject.parseObject(root.getString(Constants.ResultStruct.TASK_RESULT), TaskResult.class);
        List<Page> pages = taskResult.getPage();
        for (int j = 0; j < pages.size(); j++) {
            Page page = pages.get(j);
            if (funcEnum == RecognizeFuncEnum.TITLE) {
                Wjtz wjtz = getTitle(root, page);
                if (wjtz != null) {
                    list.add(wjtz);
                    break;
                }
            }
            else {
                list.addAll(getItem(funcEnum, page));
            }
        }
        return list;

    }

    private List<Wjtz> getItem(RecognizeFuncEnum funcEnum, Page page) {
    	List<Wjtz> list = new ArrayList<>();
        String key = funcEnum.toString();
        switch (funcEnum) {
            case Seal:
            case Fingerprint:
                key = WordUtils.capitalize(funcEnum.name());
                JSONObject obj=JSONObject.parseObject(JSON.toJSONString(page));
                JSONArray seals = obj.getJSONArray(key);
                if (seals != null && seals.size() > 0) {
                    for (int index = 0; index < seals.size(); index++) {
                        JSONObject seal = seals.getJSONObject(index);
                        JSONObject rect = seal.getJSONObject("rect");
                        list.add(new Wjtz(funcEnum.getCode(), rect.getInteger("x"), rect.getInteger("y"), rect.getInteger("w"),
                                rect.getInteger("h")));
                    }
                }
                break;
            case SIGNATURE:
            	List<TextRegion> textRegion=page.getTextRegion();
				for (TextRegion t : textRegion) {
					List<Textline> textlineList = t.getTextline();
					if (CollectionUtils.isEmpty(textlineList)) {
						continue;
					}
					// 过滤出手写体部分
					List<Textline> handWriteTextline = textlineList.stream()
							.filter(v -> Constants.ResultStruct.HANDWRITE.equals(v.getType()))
							.collect(Collectors.toList());
					if (CollectionUtils.isNotEmpty(handWriteTextline)) {
						for (Textline textline : handWriteTextline) {
							Rect rect = textline.getRect();
							list.add(new Wjtz(funcEnum.getCode(), rect.getX(), rect.getY(), rect.getW(), rect.getH()));
						}
					}
				}
            	
        }
        return list;
    }

    private Wjtz getTitle(JSONObject root, Page page) {
        // 获取标题
        List<AcDto> acList = new ArrayList<>(0);
        AcDto acDto = new AcDto();
        acDto.setId(Constants.WjsbItemType.SBBT);
        acDto.setOcr_result(root);
        acList.add(acDto);
        CatalogInfoDTO catalogInfoDto = contClient.request(acList);

        if (catalogInfoDto != null && catalogInfoDto.getCatalogInfo() != null &&
                CollectionUtils.isNotEmpty(catalogInfoDto.getCatalogInfo().getCatalog())) {
            Catalog catalog = catalogInfoDto.getCatalogInfo().getCatalog().get(0);
            String title = catalog.getTitle().toString();

            int x, y, w, h;
            List<TextRegion> textRegions = page.getTextRegion();
            if (CollectionUtils.isEmpty(textRegions)) {
                return null;
            }

            for (TextRegion textRegion : textRegions) {
                List<Textline> textlines = textRegion.getTextline();
                if (CollectionUtils.isEmpty(textlines)) {
                    continue;
                }

                for (Textline textline : textlines) {
                    if (CollectionUtils.isEmpty(textline.getSent())) {
                        continue;
                    }

                    String value = textline.getSent().get(0).getValue();
                    if (value.equals(title)) {
                        x = textline.getRect().getX();
                        y = textline.getRect().getY();
                        h = textline.getRect().getH();
                        w = textline.getRect().getW();

                        return new Wjtz(RecognizeFuncEnum.TITLE.getCode(), x, y, w, h);
                    }
                }
            }
        }
        return null;
    }
}
